package com.lancoo.answer.widget.span;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.text.style.DynamicDrawableSpan;
import android.text.style.ImageSpan;
import android.util.Log;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.lancoo.answer.R;
import com.lancoo.answer.util.DpUtils;
import com.rxjava.rxlife.RxLife;

import java.lang.reflect.Field;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

import io.reactivex.Single;
import io.reactivex.android.schedulers.AndroidSchedulers;

/**
 * Created by pengmi on 2021/12/31 11:52
 * Description:
 */
public class UrlImageSpan extends ImageSpan {

    private String url;
    private TextView tv;
    private boolean picShowed;

    public UrlImageSpan(Context context, String url, TextView tv) {
        super(context, R.mipmap.ev_ic_load_music);
        this.url=url;
        this.tv=tv;
    }

    @Override
    public Drawable getDrawable() {
//        Context context = tv.getContext();
//        Bitmap bitmap = createBitmap(context.getApplicationContext(), url);
//        if(bitmap!=null){
//            int orginalWidth = DpUtils.dip2px(tv.getContext(),bitmap.getWidth());
//            int width= Math.min(orginalWidth, DpUtils.getWidthInPx(tv.getContext())/2);
//            Bitmap zoom=zoom(bitmap,width);
//            BitmapDrawable result=new BitmapDrawable(zoom);
//            result.setBounds(0,0,zoom.getWidth(), zoom.getHeight());
//            return result;
//        }
//
//        return super.getDrawable();
        if(picShowed){
            return super.getDrawable();
        }
        Glide.with(tv.getContext()).asBitmap().load(url).into(new SimpleTarget<Bitmap>() {
            @Override
            public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                try{
                    picShowed=true;
                    Single.timer(1, TimeUnit.MILLISECONDS)
                            .observeOn(AndroidSchedulers.mainThread())
                            .as(RxLife.as(tv,true))
                            .subscribe(aLong -> {
                                if(tv==null){
                                    Log.e("error","图片没有绘制"+url);
                                    return;
                                }
                                Log.e("error","图片绘制了"+url);
                                int orginalWidth = DpUtils.dip2px(tv.getContext(),resource.getWidth());
                                Resources resources = tv.getContext().getResources();
                                int width= Math.min(orginalWidth, DpUtils.getWidthInPx(tv.getContext())/2);
                                Log.e("error","orginalWidth:"+orginalWidth);
                                Bitmap zoom=zoom(resource,width);
                                BitmapDrawable b=new BitmapDrawable(resources,zoom);
                                b.setBounds(0,0,b.getIntrinsicWidth(),b.getIntrinsicHeight());
                                Field mDrawable;
                                Field mDrawableRef;
                                mDrawable=ImageSpan.class.getDeclaredField("mDrawable");
                                mDrawable.setAccessible(true);
                                mDrawable.set(UrlImageSpan.this,b);
                                mDrawableRef= DynamicDrawableSpan.class.getDeclaredField("mDrawableRef");
                                mDrawableRef.setAccessible(true);
                                mDrawableRef.set(UrlImageSpan.this,null);
                                Log.e("error","txt:"+tv.getText());
                                CharSequence text = tv.getText();
                                tv.clearComposingText();
                                tv.setText(text);
                                tv.requestLayout();
                            },throwable -> {});
                }catch (Exception e){
                    e.printStackTrace();
                }

            }
        });
        return super.getDrawable();

    }

    public static Bitmap zoom(Bitmap bmp,int newW){
        int width = bmp.getWidth();
        int height = bmp.getHeight();

        float scale=((float) newW)/width;

        Matrix matrix=new Matrix();
        matrix.postScale(scale,scale);
        Bitmap newBitmap=Bitmap.createBitmap(bmp,0,0,width,height,matrix,true);
        return newBitmap;
    }


    private static Bitmap createBitmap(Context context, Object model) {
        try {
            int size = (int) (DpUtils.getWidthInPx(context)-DpUtils.dip2px(context,24));
            RequestOptions options = RequestOptions.overrideOf(size);
            return Glide.with(context)
//                    .setDefaultRequestOptions(options)
                    .asBitmap()
                    .load(model)
                    .submit()
                    .get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return null;
    }
}
